/**
 * 
 */
package br.com.pim.action;

import java.sql.Connection;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;

import br.com.pim.connection.ConnectionFactory;
import br.com.pim.dao.FornecedorDAO;
import br.com.pim.dao.MarcaDAO;
import br.com.pim.form.MarcaForm;
import br.com.pim.model.MarcaModel;
import br.com.pim.util.ConstantesGerais;

/**
 * @author douglas.peixoto
 * 
 */
public class MarcaAction extends DispatchAction {

	public ActionForward iniciar(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse resp) throws Exception {

		Connection myConn = null;
		MarcaDAO mDAO = null;
		FornecedorDAO fDAO = null;
			try {
				myConn = new ConnectionFactory().getConnectionMySQL();
				mDAO = new MarcaDAO(myConn);
				req.setAttribute("LISTA_MARCAS", mDAO.buscarTodos());
				fDAO = new FornecedorDAO(myConn);
				req.setAttribute("LISTA_FORNECEDORES", fDAO.buscarTodos());
			} finally {
				myConn.close();
			}

		return mapping.getInputForward();

	}

	public ActionForward inserir(ActionMapping mapping, ActionForm form,
			HttpServletRequest req, HttpServletResponse resp) throws Exception {
		
		MarcaForm mForm = (MarcaForm) form;
		MarcaModel mModel = null;
		MarcaDAO mDAO = null;
		Connection myConn = null;
		
			try{
				
				myConn = new ConnectionFactory().getConnectionMySQL();
				mDAO = new MarcaDAO(myConn);
				mModel = mForm.getMarca();
				
				if(!(mModel.getCdFornecedor().getCdFornecedor() == -1 || mModel.getNmMarca().equals(""))){
					mDAO.inserir(mModel);
				}else{
					ActionErrors errors = new ActionErrors();
						errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage(ConstantesGerais.ERROR_GENERICO));
						super.saveErrors(req, errors);
						super.saveMessages(req, new ActionMessages());
				}
					
				
				this.iniciar(mapping, mForm, req, resp);
				
			}finally{
				if (myConn != null) {
					myConn.close();
				}
			}
		
		
		return mapping.getInputForward();
	}
	
}
